# -*- coding: UTF-8 -*-
# author: notedit
# date: 20110711
# filename: ooclient.py

'''oocrpc python client'''

class OocRpcClient(object):

    def __init__(self,host='localhost',port=27017):
        from pymongo import Connection
        self.__connection = Connection(host,port,max_pool_size=10)
        return 

    def __getattr__(self,funcname):
        if funcname.startswith('_'):
            return object.__getitem__(self,funcname)
        else:
            func = lambda *args,**kwargs:self.__call__(funcname,*args,**kwargs)
            func__name__ = 'OocRpcClient.' + funcname
            return func

    def __call__(self,funcname,*args,**kwargs):
        params = map(lambda xx:repr(xx),args)
        for (k,v) in kwargs.items():
            params.append('%s=%s'%(k,repr(v)))
        querydict = {'result':'%s(%s)'%(funcname,','.join(params))}
        try:
            collection = self.__connection['notedit']['notedit']
            ret = collection.find_one(querydict)
            return ret['result']
        finally:
            if self.__connection:
                self.__connection.end_request()
